package top.gaui.nurse.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import top.gaui.nurse.entity.Execution;
import top.gaui.nurse.entity.Nurse;
import top.gaui.nurse.repository.ExecutionRepository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Fujie_Zeng
 * @version 1.0
 * @date 2020/4/21 5:19
 */
@RestController
@RequestMapping("/execution")
public class ExecutionHandler {
    @Autowired
    private ExecutionRepository executionRepository;

    @GetMapping("/findWork/{num}")
    public Integer findWork(@PathVariable Integer num){
        return executionRepository.countByNum(num);
    }
    @GetMapping("/findDo/{num}")
    public  Integer findDo(@PathVariable Integer num){
        String s="已完成";
        return executionRepository.countByNumAndState(num,s);
    }

    @PostMapping ({"/find/{department}/{page}/{size}",
            "/find/{type}/{department}/{page}/{size}",
            "/find/{state}/{department}/{page}/{size}",
            "/find/{type}/{state}/{department}/{page}/{size}"})
    public Page<Execution> findAllByName(@PathVariable(required = false)String type, @PathVariable(required = false)String state, @PathVariable String department, @PathVariable Integer page, @PathVariable Integer size) {
        Specification<Execution> specification = new Specification<Execution>() {
            @Override
            public Predicate toPredicate(Root<Execution> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (type !=null) {
                    predicateList.add(criteriaBuilder.equal(root.get("type").as(String.class), type));
                }
                if (state !=null) {
                    predicateList.add(criteriaBuilder.equal(root.get("state").as(String.class), state));
                }
                if(department != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("department").as(String.class),department));
                }

                Predicate[] pre = new Predicate[predicateList.size()];
                criteriaQuery.orderBy(criteriaBuilder.asc(root.get("id")));
                return criteriaQuery.where(predicateList.toArray(pre)).getRestriction();
            }
        };
        PageRequest request = PageRequest.of(page-1,size);
        return executionRepository.findAll(specification, request);
    }
}
